
#import "PercentCurrentDataModel.h"
#import "MetricsItem.h"
#import <stdlib.h>


@implementation PercentCurrentDataModel

@synthesize metricsItems = _metricsItems;
@synthesize  numberOfData;

@synthesize labels = _labels;
@synthesize monthlyKeys=_monthlyKeys;



-(id) init{
    
     if (self = [super init]){
     //Set up 3 years of data from today back    
     NSDateFormatter *df = [[NSDateFormatter alloc]init];  
    [df setDateFormat:@"MMddyyyy"];  
    
    NSDate * newYearDay2012 = [df dateFromString:@"01012012"];
    NSDate * today = [NSDate date];
    NSString *todayString = [df stringFromDate:today];
    NSString *startDateString = [[todayString substringToIndex:4] stringByAppendingString:@"2009"];
    NSDate *startDate = [df dateFromString:startDateString];
    NSDate *endOfYear2009=[df dateFromString:@"12312009"];
    
    NSUInteger daysin2012 = [self getNumberOfDaysFrom:newYearDay2012 to:today] +1;
    NSUInteger daysin2009 = [self getNumberOfDaysFrom:startDate to:endOfYear2009] +1;
    self.numberOfData= daysin2009 + 365 + 365 + daysin2012;
         
         
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMdd"];	
   _metricsItems = [NSMutableDictionary dictionaryWithCapacity:2000];
    
    NSTimeInterval oneDay = 24 * 60 * 60;
    
    double percentCurrent=26;
    double percent1To30DaysDelinquent=25;		
    double percent31To60DaysDelinquent=20;
    double percent61To90DaysDelinquent=20;
    double percent90OverDaysDelinquent=0;
    
    for (int d=0; d < self.numberOfData; d++) 
    {  
        
        
        NSDate *itemDate = [startDate dateByAddingTimeInterval:(oneDay * d)]; 
        
        MetricsItem *item = [[MetricsItem alloc]init];
        item. itemDate = itemDate;
       		
        NSString *itemDateString = [dateFormatter stringFromDate:itemDate];
        
        
        percentCurrent =[self  getNextValueByBand:percentCurrent max:50 min:20];
        percent1To30DaysDelinquent=[self  getNextValueByBand:percent1To30DaysDelinquent max:20 min:10];		
        percent31To60DaysDelinquent=[self  getNextValueByBand:percent31To60DaysDelinquent max:20 min:6];	
        percent61To90DaysDelinquent=[self  getNextValueByBand:percent61To90DaysDelinquent max:20 min:8];
        
        if (percentCurrent + percent1To30DaysDelinquent + percent31To60DaysDelinquent >= 90) {
            percent1To30DaysDelinquent = percent1To30DaysDelinquent - random()%5;
            percent31To60DaysDelinquent = percent31To60DaysDelinquent - random()%5;
            percent31To60DaysDelinquent = random()%10;
        }
        
        percent90OverDaysDelinquent=100-percentCurrent-percent1To30DaysDelinquent-
        percent31To60DaysDelinquent-percent61To90DaysDelinquent;
        
        
        item.timeIntervalSinceToday = oneDay * (numberOfData-d-1);
        item.timeIntervalSinceStart = oneDay * d;
        item.percentCurrent =[NSNumber numberWithDouble:percentCurrent]; 		   
        item.percent1To30DaysDelinquent =[NSNumber numberWithDouble:percent1To30DaysDelinquent]; 
        item.percent31To60DaysDelinquent = [NSNumber numberWithDouble:percent31To60DaysDelinquent]; 
        item.percent61To90DaysDelinquent = [NSNumber numberWithDouble:percent61To90DaysDelinquent]; 
        item.percent90OverDaysDelinquent = [NSNumber numberWithDouble:percent90OverDaysDelinquent]; 
        
        //NSLog(@"percent90OverDaysDelinquent = %f", item.percent90OverDaysDelinquent.floatValue);

        [_metricsItems setObject: item forKey: itemDateString];
        
    };  
         NSArray *dailykeys = [_metricsItems allKeys];
         NSArray *sortedKeys = [dailykeys sortedArrayUsingSelector:@selector(compare:)];  
         
         //prepare priorYearPercent data
         for (int d = 0; d < [dailykeys count]; d++){
             if (d > 364){
                 MetricsItem *currentData = [_metricsItems objectForKey: [sortedKeys objectAtIndex:d]];
                 MetricsItem *priorData = [_metricsItems objectForKey: [sortedKeys objectAtIndex:(d-365)]];
                 currentData.priorYearPercentCurrent = priorData.percentCurrent;
             } else {
                 MetricsItem *currentData = [_metricsItems objectForKey: [sortedKeys objectAtIndex:d]];
                 currentData.priorYearPercentCurrent = [NSNumber numberWithInt:0];
             }  
         }
         
         //prepare data for the slider plot
         NSMutableArray *selectedDailyKeys = [NSMutableArray arrayWithCapacity:500]; 
         
         MetricsItem *firsDayData = [_metricsItems objectForKey:[sortedKeys objectAtIndex:0]];
         int firstDayInterval = firsDayData.timeIntervalSinceStart;
         //NSLog(@"firstDayInterval = %i",firstDayInterval);
         
         for (int s=0; s < [sortedKeys count]; s++) {
             MetricsItem *data = [_metricsItems objectForKey:[sortedKeys objectAtIndex:s]];
             int dataInterval = data.timeIntervalSinceStart - firstDayInterval;
             //NSLog(@"s=%i, date: %@",s, [sortedKeys objectAtIndex:s]);
             if ( dataInterval % (60 * 60 * 24 * 15) == 0 ){
                 [selectedDailyKeys addObject: [sortedKeys objectAtIndex:s]];
                 //NSLog(@"date added to slider: %@",[sortedKeys objectAtIndex:s]);
             }
         };
        // NSLog(@"count = %i",[selectedDailyKeys count]);
         
         
         
         _monthlyKeys = [NSArray arrayWithArray:selectedDailyKeys];}
    
    return self;
}

- (double) getNextValueByBand:(double ) lastRand  max:(float ) max min: (float) min
{
    lastRand = random()%2==1 ? lastRand + (random()%100)*0.01 : lastRand - (random()%100)*0.01;
    
    lastRand = lastRand > max ? lastRand - random()%4 : (lastRand < min ? lastRand + random()%4 : lastRand);
    
    return lastRand;
}



-(NSUInteger)getNumberOfDaysFrom:(NSDate *)fromDate to:(NSDate *)toDate
{
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *components = [gregorian components:NSDayCalendarUnit
                                                fromDate:fromDate
                                                toDate:toDate options:0];
    
    NSInteger days = [components day];
    
    return days;
    
}

@end
